/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sea.util;

import java.awt.Frame;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import sea.SimHyAGui;
import sea.plot.PlotNewFixForm;
import simhya.script.ExploredSymbol;
import simhya.script.Symbol;

/**
 * 
 * The help file
 * 
 * @author  Zhirun Ding
 * 
 * Created on 11/07/2012
 * 
 */

public class WinHelper {
    //show dialog in mainframe of application
    public static void showDialog(JDialog dialogVariable, Class dialogInstance) {
        JFrame mainFrame = SimHyAGui.getApplication().getMainFrame();
        if (dialogVariable == null) {                
            try {
                //create instance by reflect
                Class[] args = {Frame.class, boolean.class};
                Constructor constructor = dialogInstance.getConstructor(args);
                //Object[] initargs = {mainFrame, true};
                Object[] initargs = {null, true};

                dialogVariable = (JDialog) constructor.newInstance(initargs);
                dialogVariable.setLocationRelativeTo(mainFrame);
                
                
                
                //System.out.println(dialogVariable.getName());
                if (dialogVariable.getName().equals("SimulateForm")) {                    
                    PublicParam.SimulateForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateForm")) {                    
                    PublicParam.SimulateForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateHAdvancedForm")) {                    
                    PublicParam.SimulateHAdvancedForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateHDynswForm")) {                    
                    PublicParam.SimulateHDynswForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateODEForm")) {                    
                    PublicParam.SimulateODEForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateSGForm")) {                    
                    PublicParam.SimulateSGForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateSStatisticsForm")) {                    
                    PublicParam.SimulateSStatisticsForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateSTrasectoryForm")) {                    
                    PublicParam.SimulateSTrasectoryForm = dialogVariable;
                } else if (dialogVariable.getName().equals("SimulateSaveForm")) {                    
                    PublicParam.SimulateSaveForm = dialogVariable;
                } else if (dialogVariable.getName().equals("ExploreRangeForm")) {                    
                    PublicParam.ExploreRangeForm = dialogVariable;
                } else if (dialogVariable.getName().equals("ExploreOutputTypeForm")) {                    
                    PublicParam.ExploreOutputTypeForm = dialogVariable;
                } else if (dialogVariable.getName().equals("Plot3DForm")) {                    
                    PublicParam.Plot3DForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotDetermForm")) {                    
                    PublicParam.PlotDetermForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotForm")) {                    
                    PublicParam.PlotForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotHistForm")) {                    
                    PublicParam.PlotHistForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotNewFixForm")) {                    
                    PublicParam.PlotNewFixForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotPhaseForm")) {                    
                    PublicParam.PlotPhaseForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotSimulationTypeForm")) {                    
                    PublicParam.PlotSimulationTypeForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotStatexpForm")) {  
                    PublicParam.PlotStatexpForm = dialogVariable;
                } else if (dialogVariable.getName().equals("PlotStatisticsForm")) {                    
                    PublicParam.PlotStatisticsForm = dialogVariable;
                } else if (dialogVariable.getName().equals("LinearNoiseQueryForm")) {                    
                    PublicParam.LinearNoiseQueryForm = dialogVariable;
                } 
                
            } catch (InstantiationException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InvocationTargetException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(WinHelper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        SimHyAGui.getApplication().show(dialogVariable);
    }    

    public static void closeFormAfterCommand() {
        //simulate
        if (PublicParam.SimulateForm != null) {
            PublicParam.SimulateForm.dispose();
            PublicParam.SimulateForm = null;
        }
        if (PublicParam.SimulateSGForm != null) {
            PublicParam.SimulateSGForm.dispose();
            PublicParam.SimulateSGForm = null;
        }
        if (PublicParam.SimulateODEForm != null) {
            PublicParam.SimulateODEForm.dispose();
            PublicParam.SimulateODEForm = null;
        }
        if (PublicParam.SimulateHDynswForm != null) {
            PublicParam.SimulateHDynswForm.dispose();
            PublicParam.SimulateHDynswForm = null;
        }
        if (PublicParam.SimulateHAdvancedForm != null) {
            PublicParam.SimulateHAdvancedForm.dispose();
            PublicParam.SimulateHAdvancedForm = null;
        }
        //explore
//        if (PublicParam.ExploreRangeForm != null) {
//            PublicParam.ExploreRangeForm.dispose();
//            PublicParam.ExploreRangeForm = null;
//        }
        if (PublicParam.ExploreOutputTypeForm != null) {
            PublicParam.ExploreOutputTypeForm.dispose();
            PublicParam.ExploreOutputTypeForm = null;
        }
        //plot
        if (PublicParam.Plot3DForm != null) {
            PublicParam.Plot3DForm.dispose();
            PublicParam.Plot3DForm = null;
        }
//        if (PublicParam.PlotDetermForm != null) {
//            PublicParam.PlotDetermForm.dispose();
//            PublicParam.PlotDetermForm = null;
//        }
        if (PublicParam.PlotForm != null) {
            PublicParam.PlotForm.dispose();
            PublicParam.PlotForm = null;
        }
        if (PublicParam.PlotHistForm != null) {
            PublicParam.PlotHistForm.dispose();
            PublicParam.PlotHistForm = null;
        }
        if (PublicParam.PlotNewFixForm != null) {
            PublicParam.PlotNewFixForm.dispose();
            PublicParam.PlotNewFixForm = null;
        }
//        if (PublicParam.PlotPhaseForm != null) {
//            PublicParam.PlotPhaseForm.dispose();
//            PublicParam.PlotPhaseForm = null;
//        }
        if (PublicParam.PlotSimulationTypeForm != null) {
            PublicParam.PlotSimulationTypeForm.dispose();
            PublicParam.PlotSimulationTypeForm = null;
        }
//        if (PublicParam.PlotStatexpForm != null) {
//            PublicParam.PlotStatexpForm.dispose();
//            PublicParam.PlotStatexpForm = null;
//        }
        if (PublicParam.PlotStatisticsForm != null) {
            PublicParam.PlotStatisticsForm.dispose();
            PublicParam.PlotStatisticsForm = null;
        }
        //save
        if (PublicParam.SimulateSaveForm != null) {
            PublicParam.SimulateSaveForm.dispose();
            PublicParam.SimulateSaveForm = null;
        }
        if (PublicParam.SimulateSStatisticsForm != null) {
            PublicParam.SimulateSStatisticsForm.dispose();
            PublicParam.SimulateSStatisticsForm = null;
        }
        if (PublicParam.SimulateSTrasectoryForm != null) {
            PublicParam.SimulateSTrasectoryForm.dispose();
            PublicParam.SimulateSTrasectoryForm = null;
        }
    }
    
    public static void closeAdvancedFormAfterCommand() {
        if (PublicParam.ExploreRangeForm != null) {
            PublicParam.ExploreRangeForm.dispose();
            PublicParam.ExploreRangeForm = null;
        }
        if (PublicParam.LinearNoiseQueryForm != null) {
            PublicParam.LinearNoiseQueryForm.dispose();
            PublicParam.LinearNoiseQueryForm = null;
        }
    }
    
    
    public static void initListbox(JList listbox, ArrayList<Symbol> vars) {
        initListbox(listbox, vars, true);
    }
    //init list box by ArrayList<Symbol>
    public static void initListbox(JList listbox, ArrayList<Symbol> vars, boolean removeAll) {
        //remove all items form listbox
        DefaultListModel lm = new DefaultListModel();
        if (removeAll) {
            listbox.removeAll();
        } else {
            lm = (DefaultListModel)listbox.getModel();
        }
        
        //add all mode variable to listbox
        for (int i = 0; i < vars.size(); i++) {
            lm.add(i, vars.get(i).name);    
            //System.out.println(vars.get(i).name + "=" + vars.get(i).value);
        }
        
        //bind all model variable to listbox
        listbox.setModel(lm);
    }
    
    public static void initListbox2(JList listbox, ArrayList<String> vars) {
        //remove all items form listbox
        listbox.removeAll();
        DefaultListModel lm = new DefaultListModel();
        
        //add all mode variable to listbox
        for (int i = 0; i < vars.size(); i++) {
            lm.add(i, vars.get(i));    
            //System.out.println(vars.get(i).name + "=" + vars.get(i).value);
        }
        
        //bind all model variable to listbox
        listbox.setModel(lm);
    }
    
    public static void initListbox3(JList listbox, ArrayList<ExploredSymbol> vars) {
        //remove all items form listbox
        listbox.removeAll();
        DefaultListModel lm = new DefaultListModel();
        
        //add all mode variable to listbox
        for (int i = 0; i < vars.size(); i++) {
            lm.add(i, vars.get(i).name);    
            //System.out.println(vars.get(i).name + "=" + vars.get(i).value);
        }
        
        //bind all model variable to listbox
        listbox.setModel(lm);
    }
    
    public static void initTable(JTable table, ArrayList<ExploredSymbol> evars) {
        DefaultTableModel tm = (DefaultTableModel)table.getModel();
        //remove all rows
        for (int i = tm.getRowCount() - 1; i >= 0; i--) {
            tm.removeRow(i);
        }
        
        //add new data
        String s = "";
        for (int i = 0; i < evars.size(); i++) {
            if (evars.get(i).values != null && evars.get(i).values.size() > 0) {
                s = evars.get(i).values.toString();
            } else {
                //range=[p1=1:10#10,p2=1:1e4#5log]
                if (evars.get(i).first > 0) {
                    s = String.valueOf(evars.get(i).first);
                }
                if (evars.get(i).last > 0 && evars.get(i).points > 0) {
                    s += ":" + String.valueOf(evars.get(i).last)
                            + "#" + String.valueOf(evars.get(i).points);
                }
                if (evars.get(i).logScale) {
                    s += "log";
                }
            }
            
            //set default value
            Object[] rowData = new Object[]{false, evars.get(i).name, s};        
            //add row to table
            tm.addRow(rowData);
        }
    }
        
    public static void setListSelectall(JList list, String exceptvar) {
        DefaultListModel lm = (DefaultListModel)list.getModel();
        ArrayList<Integer> al = new ArrayList<Integer>();
        //int[] selectedIndexes = new int[lm.getSize()];
        for (int i = 0; i < lm.getSize(); i++) {
            if (exceptvar.length() == 0 || (exceptvar.length() > 0 && !exceptvar.endsWith(lm.get(i).toString()))) {
                al.add(i);
            }
        }
        if (al.size() > 0) {
            int[] selectedIndexes = new int[al.size()];
            for (int i = 0; i < al.size(); i++) selectedIndexes[i] = al.get(i).intValue();
            
            //set all items selected
            list.setSelectedIndices(selectedIndexes);
        }
    }
    
    public static void setListSelectItem(JList list, String selectvar) {
        DefaultListModel lm = (DefaultListModel)list.getModel();
        
        for (int i = 0; i < lm.getSize(); i++) {
            if (selectvar.equals(lm.get(i).toString())) {
                list.setSelectedIndex(i);
            }
        }        
    }

    public static void removeFromListbox(JList listbox, String varName) {
        DefaultListModel lm = (DefaultListModel)listbox.getModel();
        for (int i = 0; i < lm.getSize(); i++) {
            if (lm.get(i).toString().endsWith(varName)) {
                lm.remove(i);
                break;
            }
        }
    }
    
    public static DefaultTableModel copyTableModel(DefaultTableModel tmSource) {
        DefaultTableModel tmDes = new DefaultTableModel();
        //add column
        for (int i = 0; i < tmSource.getColumnCount(); i++) {
            tmDes.addColumn(tmSource.getColumnName(i));
        }
        //copy data
        for (int i = 0; i < tmSource.getRowCount(); i++) {
            ArrayList al = new ArrayList();
            for (int j = 0; j < tmSource.getColumnCount(); j++) {
                al.add(tmSource.getValueAt(i, j));
            }
            tmDes.addRow(al.toArray());
        }
        
        return tmDes;
    }
    
    public static void showHelp(String fileName) {
        if (PublicParam.HelpFrame == null) {
            PublicParam.HelpFrame = new HelpFrame();
        }
        
        String url = "file:///" + System.getProperty("user.dir") + "/uihelp/" + fileName + ".html";
        //System.out.println(url);
        
        ((HelpFrame)PublicParam.HelpFrame).setPage(url);
        ((HelpFrame)PublicParam.HelpFrame).setVisible(true);
    }

    public static DefaultTableModel addVariableToFixList(JTable fixlistTable) {
        //add fix variable
        if (PublicParam.PlotNewFixForm != null) {
            Object[] rowData = ((PlotNewFixForm)PublicParam.PlotNewFixForm).toFixListVariable();
            //System.out.println(rowData.toString());
            if (rowData != null) {
                DefaultTableModel dtm = ((DefaultTableModel)fixlistTable.getModel());
                for (int i = 0; i < dtm.getRowCount(); i++) {
                    if (dtm.getValueAt(i, 1).toString().endsWith(rowData[1].toString())) {
                        //this param has existed
                        dtm.removeRow(i);
                    }
                }
                //add new row
                ((DefaultTableModel)fixlistTable.getModel()).addRow(rowData);
                //copy full table model to public param
                return WinHelper.copyTableModel(((DefaultTableModel)fixlistTable.getModel()));
            }
        }
        return null;
    }  
    
    //selectedParams=>ki,kr
    public static void refreshItemOfFixList(JTable fixlistTable, 
            DefaultTableModel fullFixTableModel, String selectedParams) {
        if (selectedParams.length() > 0) {
            //in the table, parameters selected in explored params list should be disabled.
            DefaultTableModel thisTableModel = (DefaultTableModel)fixlistTable.getModel();
            //remove all data
            for(int i = thisTableModel.getRowCount() - 1; i >= 0; i--) {
                 thisTableModel.removeRow(i);
            }            
            //add data
            selectedParams = "," + selectedParams + ",";
            if (fullFixTableModel != null) {
                for(int i = 0; i < fullFixTableModel.getRowCount(); i++) {
                    String param = "," + fullFixTableModel.getValueAt(i, 1).toString() + ",";
                    if (selectedParams.indexOf(param) == -1) {
                        thisTableModel.addRow(new Object[]{fullFixTableModel.getValueAt(i, 0),
                            fullFixTableModel.getValueAt(i, 1), fullFixTableModel.getValueAt(i, 2)});           
                        break;
                    }
                }
            }
        }    
    }
}
